var FormEX = require(path.join(__dirname, 'form.js'));
var verifty = require(path.join(__dirname, 'verifty.js'));
var dialogEX = require(path.join(__dirname, '_dialog.js'));
var modalItem = require(path.join(__dirname, '_modal.js')).item;
var dialog = require('electron').remote.dialog;
var Guid = function () {
    var guid = '';
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
            guid += '-';
    }
    return guid;
};
var selectEX = FormEX.select;
var inputEX = FormEX.input;
var textareaEX = FormEX.textarea;

function looks_like_html(source) {
    // <foo> - looks like html
    var trimmed = source.replace(/^[ \t\n\r]+/, '');
    return trimmed && (trimmed.substring(0, 1) === '<');
}

function beautify(obj) {
    var source = obj.getValue(),
        output,
        opts = {
            // brace_style : "expand"
        };
    opts.indent_char = ' ';
    opts.preserve_newlines = "-1";
    if (looks_like_html(source)) {
        output = html_beautify(source, opts);
    } else {
        output = js_beautify(source, opts);
    };
    obj.setValue(output);
};
var Select = selectEX({
    showNameByDataKey: 'label',
    setValueByDataKey: 'value',
    getForm: 'value',
    "default": 'GET',
    data: [{
        label: 'GET',
        value: 'GET'
    }, {
        label: 'POST',
        value: 'POST'
    }, {
        label: 'PUT',
        value: 'PUT'
    }, {
        label: 'DELETE',
        value: 'DEL'
    }]
});


var urlSelect = selectEX({
    showNameByDataKey: 'url',
    setValueByDataKey: 'url',
    getForm: 'url',
    data: []
});

var input = inputEX({
    size: 'block',
    jude: {
        name: '标题',
        rules: []
    },
    readonly: false,
    placeholder: '请输入接口名称',
});
var textarea = textareaEX({
    size: 'block',
    jude: {
        name: '备注',
        rules: []
    },
    readonly: false,
    placeholder: ' - 请输入备注 - ',
});

var formItem = function (data, parent) {
    this.id = Guid();
    this.parent = parent;

    this.html = $('<div class="formDataList_item"></div>');
    this.key = $('<div class="formDataTitle_item"></div>');
    this.type = $('<div class="formDataTitle_item"></div>');
    this.value = $('<div class="formDataTitle_item" style="display:block"></div>');
    this.file = $('<div class="formDataTitle_item" style="display:none"></div>');
    this.delete = $('<div class="formDataTitle_item noborder" style="width:10%"><div class="botton"><i class="fa fa-trash-o"></i></div></div>');
    this.keyInput = $('<input type="text" />');
    this.key.append(this.keyInput);

    this.valueInput = $('<input type="text" />');
    this.valueFile = $('<div class="botton">上传文件</div>');

    this.value.append(this.valueInput);
    this.file.append(this.valueFile);

    this.botton = this.delete.find('.botton');
    this.botton.click(() => {
        this.parent.delete(this.id);
        this.change();
    });


    this._select = selectEX({
        showNameByDataKey: 'name',
        setValueByDataKey: 'type',
        getForm: 'type',
        data: [{
            type: 'string',
            name: 'string'
        }, {
            type: 'file',
            name: 'file'
        }],
        default: 'string',
        changeEvent: (event) => {
            var data = event.valueData.type;
            if (data == 'string') {
                this.value.css('display', 'block');
                this.valueInput.val('');
                this.file.css('display', 'none');
                this.valueFile.text('上传文件');
            } else if (data == 'file') {
                this.value.css('display', 'none');
                this.valueInput.val('');
                this.file.css('display', 'block');
                this.valueFile.text('上传文件');
            };
            this.change();
        }
    });

    this.valueFile.click(() => {
        dialog.showOpenDialog({
            title: '选择文件',
            filters: [],
            properties: ['openFile', 'createDirectory'],
        }, (filenames) => {
            if (filenames) {
                var file = filenames[0];
                var pos = file.lastIndexOf("\\");
                var name = file.substring(pos + 1);
                this.valueInput.val(file);
                this.valueFile.text(name);
                this.change();
            };
        });
    });

    this.html.append(this.key);
    this.html.append(this.type);
    this.html.append(this.value);
    this.html.append(this.file);
    this.html.append(this.delete);
    this.html.append('<div style="width:100%; height:1px; clear:both"></div>');
    this.type.append(this._select.render());


    this.valueInput.unbind().bind('input propertychange', () => {
        this.change();
    });
    this.keyInput.unbind().bind('input propertychange', () => {
        this.change();
    });

    this.setData(data);
};
formItem.prototype.get = function () {
    return {
        key: this.keyInput.val(),
        type: this._select.valueData.type,
        value: this.valueInput.val(),
    }
};
formItem.prototype.change = function () {
    this.parent.change();
};
formItem.prototype.setData = function (data) {
    this.keyInput.val(data.key);
    this._select.set(data.type);
    this.valueInput.val(data.value);
    if (data.type == 'file') {
        this.value.css('display', 'none');
        this.file.css('display', 'block');
        this.valueFile.text('上传文件');
        var pos = data.value.lastIndexOf("\\");
        var name = data.value.substring(pos + 1);
        this.valueFile.text(name);
    } else {
        this.value.css('display', 'block');
        this.file.css('display', 'none');
        this.valueFile.text('上传文件');
    };
};



var formList = function () {
    this.changeEvent = function () { };
    this.items = {};
    this.html = $('<div class="formDataLayout"></div>');
    this.title = $('<div class="formDataTitle"></div>');
    this.title.append('<div class="formDataTitle_item">key</div>');
    this.title.append('<div class="formDataTitle_item">type</div>');
    this.title.append('<div class="formDataTitle_item">value</div>');
    this.title.append('<div class="formDataTitle_item noborder" style="width:10%"><div class="botton"><i class="fa fa-plus-square-o"></i></div></div>');
    this.title.append('<div style="width:100%; height:1px; clear:both"></div>');
    this.html.append(this.title);
    this.valueBox = $('<div class="formDataListBox"></div>');
    this.html.append(this.valueBox);

    this.botton = this.html.find('.botton');
    this.botton.click(() => {
        this.newItem({
            key: '',
            type: 'string',
            value: '',
        });
    });
    this.clear();
};

formList.prototype.newItem = function (data) {
    var _item = new formItem(data, this);
    this.items[_item.id] = _item;
    this.valueBox.append(_item.html);
};

formList.prototype.clear = function () {
    this.valueBox.empty();
    this.items = {};
};
formList.prototype.setValue = function (data) {
    this.clear();
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        this.newItem(element);
    };
};

formList.prototype.delete = function (id) {
    var _item = this.items[id];
    delete this.items[id];
    _item.html.remove();
};

formList.prototype.onChange = function (event) {
    this.changeEvent = event;
};

formList.prototype.change = function () {
    var data = [];
    for (var key in this.items) {
        if (this.items.hasOwnProperty(key)) {
            var element = this.items[key];
            data.push(element.get());
        }
    };
    this.changeEvent(JSON.stringify(data));
};





var contentEX = function () {

    this.event = {
        change: function () { },
        save: function () { },
        cancel: function () { },
        getModal: function () { },
        getUrl: function () { },
        getOldDate: function () { },
    };

    // 标题元素
    this.html = $('<div id="content" class="custom-scroll theme-scroll"></div>');

    this.Mark = $('<div class="content_has_nothing"></div>');

    this.html.append(this.Mark);

    this.header = $('<div class="content_header"></div>');
    this.contentIndex = $('<input type="text" class="content_title_index" />');

    this.contentIndex.mousewheel((event) => {
        var text = parseInt(this.contentIndex.val());
        if (event.deltaY > 0) {
            var _text = text - 1;
            if (_text) {
                this.contentIndex.val(_text);
                this.change('contentIndex', _text);
            } else {
                this.contentIndex.val(1)
            };
        } else if (event.deltaY < 0) {
            var _text = text + 1;
            if (_text > 99) {
                this.contentIndex.val(99);
            } else {
                this.contentIndex.val(_text);
                this.change('contentIndex', _text);
            };
        };
    });

    this.contentIndex.blur(() => {
        var _$index = this.contentIndex.val();
        _$index = parseInt(_$index);
        if (!_$index) {
            this.contentIndex.val(1);
            this.change('contentIndex', 1);
        } else {
            this.contentIndex.val(_$index);
            this.change('contentIndex', _$index);
        };
    });


    this.contentIndex.click(() => {
        var _$index = this.contentIndex.val();
        if (_$index == 1) {
            this.contentIndex.val('');
        };
    });




    this.title = $('<div class="content_title">测试接口名称</div>');
    this.titleInput = $('<div class="content_title_input form_box" tyle="display:none"></div>');
    this.titleInputObj = input;
    this.titleInput.append(this.titleInputObj.render());

    this.title.click(() => {
        this.titleInputObj.element.css('width', this.title.width() + 'px');
        this.title.css('display', 'none');
        this.titleInput.css('display', 'block');
        this.titleInputObj.element.focus();
        if (this.title.text() == '请输入接口名称') {
            this.titleInputObj.set('');
        } else {
            this.titleInputObj.set(this.title.text());
        };
    });

    this.titleInputObj.element.blur(() => {
        this.title.css('display', 'block');
        this.titleInput.css('display', 'none');
        this.titleInputObj.get((error, doc) => {
            if (error) {
                dialogEX({
                    title: '警告',
                    body: '<div style="padding:20px;">' + error + '</div>',
                    buttons: [{
                        text: '确定',
                        event: (event) => {
                            event.close();
                        },
                    }],
                    width: 400,
                    height: 200,
                });
            } else {
                if (doc == null || doc == '') {
                    this.title.text('请输入接口名称');
                    this.change('title', '请输入接口名称');
                } else if (this.title.text() != doc) {
                    this.title.text(doc);
                    this.change('title', doc);
                };
            }
        });
    });

    // 简介元素
    this.description = $('<div class="content_description"></div>');
    this.descriptionTextarea = $('<div class="content_description_textarea" style="display:none"></div>');
    this.descriptionTextareaObj = textarea;
    this.descriptionTextarea.append(this.descriptionTextareaObj.render());

    this.description.click(() => {
        this.descriptionTextareaObj.element.css('width', this.description.width() + 'px');
        this.description.css('display', 'none');
        this.descriptionTextarea.css('display', 'block');
        this.descriptionTextareaObj.element.focus();
        this.descriptionTextareaObj.set(this.description.text() == ' - 请输入备注 - ' ? '' : this.description.text());
    });

    this.descriptionTextareaObj.element.blur(() => {
        this.description.css('display', 'block');
        this.descriptionTextarea.css('display', 'none');
        this.descriptionTextareaObj.get((error, doc) => {
            this.description.scrollTop(0);
            if (error) {
                dialogEX({
                    title: '警告',
                    body: '<div style="padding:20px;">' + error + '</div>',
                    buttons: [{
                        text: '确定',
                        event: (event) => {
                            event.close();
                        },
                    }],
                    width: 400,
                    height: 200,
                });

            } else {
                if (this.description.text() != doc) {
                    this.change('description', doc);
                    this.description.text(doc ? doc : ' - 请输入备注 - ');
                };
            }
        });
    });

    // 头部块渲染
    this.header.append(this.contentIndex).append(this.title).append(this.titleInput).append(this.description).append(this.descriptionTextarea);


    // 功能条块
    this.bar = $('<div class="content_bar"></div>');

    // 下拉菜单块
    this.selectBox = $('<div class="content_select_box"></div>');
    this.contentType = Select;
    this.contentType.get((error, doc) => {
        this.contentType.name.attr('class', 'form_select_name ' + doc);
    });
    this.contentType.options.changeEvent = (event) => {
        event.get((error, doc) => {
            event.name.attr('class', 'form_select_name ' + doc);
            this.change('contentType', doc);
            this.reSizeEditor();
        });
    };
    // 下拉菜单渲染
    this.selectBox.append(this.contentType.render());


    this.urlBox = $('<div class="content_url_box"></div>');
    this.urlSelect = urlSelect;
    this.urlBox.append(this.urlSelect.render());





    // 输入框块
    this.textareaBox = $('<div class="content_textarea_box"></div>');
    this.textareaShowBox = $('<div class="content_textarea_show_box"></div>');
    this.textarea = $('<div contenteditable="true" class="content_textarea" spellcheck="false" style="display:none"></div>');

    this.textareaShowBox.click(() => {
        this.textarea.css('display', 'block');
        this.textarea.focus();
    });

    this.textarea.blur(() => {
        this.textarea.css('display', 'none');
        var text = this.textarea.text();
        var _text = this.textareaShowBox.text();
        if (text != _text) {
            this.textareaShowBox.text(this.textarea.text());
            this.textarea.css('display', 'none');
            this.change('requestURL', this.textarea.html());
        };
    });

    // 格式化粘贴代码
    this.textarea.bind("paste", (a, b, c) => {
        setTimeout(() => {
            try {
                var STR = this.textarea.html().replace(/<[^>]*>/g, function (r) {
                    var _array = ['div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li']
                    var re = new RegExp(/<\//);
                    if (re.test(r)) {
                        var _return = '';
                        for (let i = 0; i < _array.length; i++) {
                            const element = _array[i];
                            if (r == ('</' + element + '>')) {
                                _return = '</div>';
                                break;
                            };
                        };
                        return _return;
                    } else {
                        var _return = '';
                        for (let i = 0; i < _array.length; i++) {
                            const element = _array[i];
                            var _length = ('<' + element).length;
                            var _str = r.substring(0, _length);
                            if (_str == ('<' + element)) {
                                _return = '<div>';
                                break;
                            };
                        };
                        return _return;
                    }
                });
                var _STR = '';

                function dismantlHtml(event) {
                    var ele = $(event);
                    var _length = ele.find('> div').length;
                    if (_length > 1) {
                        ele.find('> div').each((index, __event) => {
                            dismantlHtml($(__event));
                        });
                    } else if (_length == 1) {
                        dismantlHtml(ele.find('> div').eq(0));
                    } else if (_length == 0) {
                        var text = ele.text().replace(/\</g, '&lt').replace(/\>/g, '&gt;');
                        if (text) {
                            _STR += ('<div>' + text + '</div>' + '\n');
                        };
                    };
                };
                dismantlHtml($('<div>' + STR + '</div>'));
                this.textarea.html(_STR);
            } catch (error) {
                dialogEX({
                    title: '警告',
                    body: '<div style="padding:20px;">格式化错误,请粘贴到TXT文本后再次操作</div>',
                    buttons: [{
                        text: '确定',
                        event: (event) => {
                            event.close();
                        },
                    }],
                    width: 400,
                    height: 200,
                });

            };
        }, 50);
    });
    this.textareaBox.append(this.textareaShowBox).append(this.textarea);

    // 调用接口模块
    this.sendBox = $('<div class="content_send_box"></div>');
    this.sendEle = $('<div>Send</div>');
    this.sendingEle = $('<div class="content_sending" style="display:none;">Sending...</div>');

    this.sendEle.click(() => {
        this.send();
    })

    // 调用接口模块渲染
    this.sendBox.append(this.sendEle).append(this.sendingEle);

    this.saveBox = $('<div class="content_save_box">还原</div>');
    this.saveBox.click(() => {
        this.setOldData();
    });

    // 功能条块渲染
    this.bar.append(this.selectBox).append(this.urlBox).append(this.textareaBox).append(this.sendBox).append(this.saveBox);

    var ResponseHtml = '';
    ResponseHtml += '    <div class="content_response">';
    ResponseHtml += '        <div class="content_code_title">Response';
    ResponseHtml += '            <span class="format">Status:-- &nbsp; Time:-- ms &nbsp; Size:--B</span>';
    ResponseHtml += '        </div>';
    ResponseHtml += '        <div class="content_code">';
    ResponseHtml += '           <div class="content_code_loading" style="display:none"><div class="content_botton_cancel">取消发送</div></div>';
    ResponseHtml += '            <textarea id="Response"></textarea>';
    ResponseHtml += '        </div>';
    ResponseHtml += '    </div>';
    this.response = $(ResponseHtml);
    this.responseCodeEle = this.response.find('.content_code');
    this.responseLoading = this.response.find('.content_code_loading');
    this.responseFormat = this.response.find('.content_code_title .format');
    this.responseCancelEle = this.response.find('.content_botton_cancel');
    this.responseCancelEle.click(() => {
        this.cancel();
    });
    this.ResponseEditor = CodeMirror.fromTextArea(this.response.find('textarea')[0], {
        // theme: 'panda-syntax',
        lineNumbers: true,
        readOnly: true,
        foldGutter: true,
        lineNumbers: true,
        lineWrapping: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });


    $(window).resize(() => {
        this.reSizeEditor();
    });


    var formatDataHtml = '';
    formatDataHtml += '    <div class="content_formatData">';
    formatDataHtml += '        <div class="content_code_title">';
    formatDataHtml += '             <div class="content_tab_button json active" title="GET 传输时不发送此项">Body</div>';
    formatDataHtml += '             <div class="content_tab_button header">Header</div>';
    formatDataHtml += '             <div class="content_tab_button test">数据回调</div>';
    formatDataHtml += '             <div class="content_tab_button modalButton" title="GET 时此项无效">加载数据模型</div>';
    formatDataHtml += '             <span class="format" style="line-height:30px" title="折叠代码只有格式化后才能正确显示">格式化</span>';
    formatDataHtml += '             <div style="clear:both;height:1px"></div>';
    formatDataHtml += '             <div class="content_tab_button active application">JSON (application/json)</div>';
    formatDataHtml += '             <div class="content_tab_button form">form Data</div>';
    formatDataHtml += '             <div class="content_tab_button">&nbsp;</div>';
    formatDataHtml += '        </div>';
    formatDataHtml += '        <div style="clear:both;height:1px"></div>';
    formatDataHtml += '        <div class="content_code requesterData">';
    formatDataHtml += '            <textarea id="JSON"></textarea>';
    formatDataHtml += '        </div>';
    formatDataHtml += '        <div class="content_code requesterHeader">';
    formatDataHtml += '            <textarea id="JSON"></textarea>';
    formatDataHtml += '        </div>';
    formatDataHtml += '        <div class="content_code requesterTestObj">';
    formatDataHtml += '            <textarea id="JSON"></textarea>';
    formatDataHtml += '        </div>';
    formatDataHtml += '        <div class="content_code requesterForm"></div>';
    formatDataHtml += '    </div>';
    this.formatData = $(formatDataHtml);





    this.formatDataHeader = this.formatData.find('.content_code.requesterHeader');
    this.formatDataHeaderEditor = CodeMirror.fromTextArea(this.formatDataHeader.find('textarea')[0], {
        // theme: 'panda-syntax',
        lineNumbers: true,
        foldGutter: true,
        lineNumbers: true,
        lineWrapping: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });
    this.formatDataHeaderEditor.on('change', (event) => {
        // event.getValue();
        this.change('header', event.getValue());
    });


    this.formatDataCodeEle = this.formatData.find('.content_code.requesterData');
    this.formatDataEditor = CodeMirror.fromTextArea(this.formatDataCodeEle.find('textarea')[0], {
        // theme: 'panda-syntax',
        lineNumbers: true,
        foldGutter: true,
        lineNumbers: true,
        lineWrapping: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });
    this.formatDataEditor.on('change', (event) => {
        // event.getValue();
        this.change('requestData', event.getValue());
    });



    this.testCodeEle = this.formatData.find('.content_code.requesterTestObj');
    this.testEditor = CodeMirror.fromTextArea(this.testCodeEle.find('textarea')[0], {
        // theme: 'panda-syntax',
        lineNumbers: true,
        foldGutter: true,
        lineNumbers: true,
        lineWrapping: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
    });

    this.testEditor.on('change', (event) => {
        // event.getValue();
        this.change('code', event.getValue());
    });

    this.formatData.find('.format').click(() => {
        beautify(this.formatDataEditor);
        beautify(this.formatDataHeaderEditor);
        beautify(this.testEditor);
    });

    this.headerButton = this.formatData.find('.header');
    this.jsonButton = this.formatData.find('.json');
    this.testButton = this.formatData.find('.test');
    this.modalBottin = this.formatData.find('.modalButton');
    this.application = this.formatData.find('.application');
    this.form = this.formatData.find('.form');
    this.requesterForm = this.formatData.find('.requesterForm');
    this.requesterTestObj = this.formatData.find('.content_code.requesterTestObj');

    this.formElement = new formList();
    this.formElement.onChange((event) => {

        this.change('formData', event);
    });
    this.requesterForm.append(this.formElement.html);


    this.jsonButton.click(() => {
        this.headerButton.removeClass('active');
        this.jsonButton.addClass('active');
        this.testButton.removeClass('active');

        if (this.application.hasClass('active')) {
            this.formatDataCodeEle.css('z-index', '11');
            this.requesterForm.css('z-index', '1');
        } else {
            this.formatDataCodeEle.css('z-index', '1');
            this.requesterForm.css('z-index', '11');
        };
        this.formatDataHeader.css('z-index', '1');
        this.testCodeEle.css('z-index', '1');
        this.application.css('display', 'block');
        this.form.css('display', 'block');
    });

    this.headerButton.click(() => {
        this.headerButton.addClass('active');
        this.jsonButton.removeClass('active');
        this.testButton.removeClass('active');
        this.formatDataHeader.css('z-index', '11');
        this.formatDataCodeEle.css('z-index', '1');
        this.testCodeEle.css('z-index', '1');
        this.requesterForm.css('z-index', '1');
        this.application.css('display', 'none');
        this.form.css('display', 'none');
    });
    this.testButton.click(() => {
        this.headerButton.removeClass('active');
        this.jsonButton.removeClass('active');
        this.testButton.addClass('active');
        this.formatDataHeader.css('z-index', '1');
        this.testCodeEle.css('z-index', '11');
        this.requesterForm.css('z-index', '1');
        this.application.css('display', 'none');
        this.form.css('display', 'none');
    });

    this.application.click(() => {
        this.application.addClass('active');
        this.form.removeClass('active');
        this.change('requestType', 'json');
        this.formatDataCodeEle.css('z-index', '11');
        this.requesterForm.css('z-index', '1');
        this.formatDataHeader.css('z-index', '1');
        this.testCodeEle.css('z-index', '1');
    });
    this.form.click(() => {
        this.form.addClass('active');
        this.application.removeClass('active');
        this.change('requestType', 'form');
        this.formatDataCodeEle.css('z-index', '1');
        this.formatDataHeader.css('z-index', '1');
        this.testCodeEle.css('z-index', '1');
        this.requesterForm.css('z-index', '11');
    });

    this.modalBottin.click(() => {
        var Items = {};
        var body = $('<div class="modalContentDialog modal"></div>');
        var search = $(`
            <div class="modalContentSearchBox">
                <input  placeholder="请输入类名进行搜索">
            </div>
        `);
        var refresh = $('<div class="modalContentRefresh"><i class="fa fa-refresh"></i></div>');
        var modalBodyBox = $('<div class="modalContentBox"></div>');
        var input = search.find('input').keypress((e) => {
            if (e.which == 13) {
                var str = input.val()
                for (const key in Items) {
                    if (Items.hasOwnProperty(key)) {
                        const item = Items[key];
                        item.bodyBox.css('display', 'none');
                        if (str) {
                            if (key.indexOf(str) >= 0) {
                                item.html.css('display', 'block');
                            } else {
                                item.html.css('display', 'none');
                            };
                        } else {
                            item.html.css('display', 'block');
                        };
                    }
                };
            }
        });
        var activeObj = null;
        body.append(search).append(refresh).append(modalBodyBox);
        var renderModal = (data) => {
            Items = {};
            modalBodyBox.empty();

            for (let i = 0; i < data.length; i++) {
                const items = data[i];
                Items[items.key] = modalItem(items, function (data) {
                    if (activeObj) {
                        activeObj.unActive();
                    };
                    // data.active();
                    activeObj = data;
                }, true);
                modalBodyBox.append(Items[items.key].html);
            };
        };

        this.event.getModal((docs) => {
            renderModal(docs);
        });

        refresh.click(() => {
            input.val('');
            this.event.getModal((docs) => {
                activeObj = null;
                renderModal(docs);
            });
        });

        var typeArray = ['Long', 'Integer', 'Short', 'Byte', 'Float', 'Double', 'Boolean', 'Char', 'String', 'Date'];

        var renderData = function (data, annotate) {
            var _String = '{'
            if (annotate) {
                _String += annotate
            };

            for (let i = 0; i < data.data.length; i++) {
                var item = data.data[i];
                var __type = item.type.replace(/ /g, '');
                if ($.inArray(__type, typeArray) >= 0) {
                    _String += (item.key + ':' + '\'\',' + ' // ' + item.annotate + ' (' + item.type + ')\n');
                } else if (item.type.indexOf('List') >= 0) {
                    var _type = item.type.substring(item.type.indexOf('<') + 1, item.type.indexOf('>'));
                    if ($.inArray(_type, typeArray) >= 0) {
                        _String += (item.key + ': [],' + ' // ' + item.annotate + ' (' + item.type + ')\n');
                    } else {
                        _String += (item.key + ': [' + ' // ' + item.annotate + ' (' + item.type + ')\n');
                        if (Items.hasOwnProperty(_type)) {
                            _String += renderData(Items[_type].data);
                        } else {
                            _String += ('{},\n');
                        };
                        _String += ('],\n');
                    };
                } else {
                    if (Items.hasOwnProperty(__type)) {
                        _String += (item.key + ': ');
                        _String += renderData(Items[__type].data, ' // ' + item.annotate + ' (' + item.type + ')\n');
                        _String += ('\n');
                    } else {
                        _String += (item.key + ': {},' + ' // ' + item.annotate + ' (' + item.type + ')\n');
                    };
                }
            };
            _String += '},'

            return _String
        };

        var dialog = dialogEX({
            title: '选择数据模型',
            width: '800',
            height: '700',
            body: body,
            buttons: [{
                className: 'editorFormButton',
                event: () => {
                    if (!activeObj) {
                        dialogEX({
                            title: '警告',
                            body: '<div style="padding:20px;">请选择数据模型</div>',
                            buttons: [{
                                text: '确定',
                                event: (event) => {
                                    event.close();
                                },
                            }],
                            width: 400,
                            height: 200,
                        });
                    } else {
                        var str = renderData(activeObj.data);
                        str = (str.substring(str.length - 1) == ',') ? str.substring(0, str.length - 1) : str;
                        this.formatDataEditor.setValue(str);
                        beautify(this.formatDataEditor);
                        dialog.close();
                    }
                },
                text: '选择'
            }]
        });
    });


    this.html.append(this.header);
    this.html.append(this.bar);
    this.html.append(this.formatData);
    this.html.append(this.response);

    this.data = {
        title: '未保存接口',
        requestURL: '',
        requestData: '',
        contentType: 'GET',
        contentIndex: '1',
        parentId: '',
        description: '',
        id: '',
        code: '',
        formData: '',
        requestType: 'json',
    };
    this.status = true;
};

contentEX.prototype = {
    constructor: this,
    render: function () {
        setTimeout(() => {
            this.reSizeEditor();
        }, 20);

        setTimeout(() => {
            this.event.getUrl((docs) => {
                docs.unshift({
                    url: '(空)'
                });
                if (__CacheData__.urlSetting) {
                    this.urlSelect.setData(docs);
                    this.urlSelect.set(__CacheData__.urlSetting)
                } else {
                    this.urlSelect.setData(docs);
                    this.urlSelect.set(0)
                };
            });
        });
        return this.html;
    },
    reSetUrl: function () {
        var url = this.urlSelect.valueData.url;
        this.event.getUrl((docs) => {
            docs.unshift({
                url: '(空)'
            });
            this.urlSelect.setData(docs);
            this.urlSelect.set(url);
        });
    },
    on: function (str, event) {
        if (this.event.hasOwnProperty(str)) {
            this.event[str] = event;
        };
    },
    setLeft: function (num) {
        this.html.css('left', num + 'px');
    },
    onSave: function (event) {
        this.event.save = event;
    },
    save: function () {
        this.event.save(this.data.id);
    },
    reSizeEditor: function () {
        // this.formatData.css('display', 'block');
        // return;
        // this.contentType.get((error, doc) => {


        //     var realHeight = ((this.html.height() - 240) / 2) < 200 ? 200 : ((this.html.height() - 240) / 2);
        //     this.responseCodeEle.css('height', realHeight * 2 / 5 * 3 + 'px');
        //     this.ResponseEditor.refresh();


        //     this.formatDataCodeEle.css('height', realHeight * 2 / 5 * 2 - 30 + 'px');
        //     this.formatDataEditor.refresh();

        //     this.formatDataHeader.css('height', realHeight * 2 / 5 * 2 - 30 + 'px');
        //     this.formatDataHeaderEditor.refresh(); G


        //     this.requesterForm.css('height', realHeight * 2 / 5 * 2 - 30 + 'px');
        //     // this.formatDataHeaderEditor.refresh();

        //     this.requesterTestObj.css('height', realHeight * 2 / 5 * 2 - 30 + 'px');
        //     this.testEditor.refresh();

        //     this.formatData.css('padding-bottom', realHeight * 2 / 5 * 2 - 30 + 'px');

        //     if (doc == 'GET' || doc == 'DEL') {
        //         this.formatDataCodeEle.addClass('readOnly');
        //         this.formatDataEditor.setOption('readOnly', true);
        //     } else {
        //         this.formatDataCodeEle.removeClass('readOnly');
        //         this.formatDataEditor.setOption('readOnly', false);
        //     };

        // });
    },
    set: function (data) {
        this.data = {
            title: '未保存接口',
            requestURL: '',
            header: '',
            requestData: '',
            contentType: 'GET',
            contentIndex: '1',
            parentId: '',
            description: ' - 请输入备注 - ',
            id: '',
            code: '',
            formData: '',
            requestType: 'json',
        };
        this.data = this.data = $.extend({}, this.data, data);
        this.contentIndex.val(this.data.contentIndex);
        this.title.text(this.data.title);
        this.titleInputObj.set(this.data.title);
        this.description.text(this.data.description ? this.data.description : ' - 请输入备注 - ');
        this.descriptionTextareaObj.set(this.data.description ? this.data.description : ' - 请输入备注 - ');
        this.contentType.set(this.data.contentType, true);
        this.textarea.html(this.data.requestURL);
        this.textareaShowBox.html(this.textarea.text());
        this.formatDataEditor.setValue(this.data.requestData ? this.data.requestData : '');
        this.formatDataHeaderEditor.setValue(this.data.header ? this.data.header : '');
        this.testEditor.setValue(this.data.code ? this.data.code : '');

        if (this.data.requestType == 'json') {
            this.application.click();
        } else if (this.data.requestType == 'form') {
            this.form.click();
        };

        this.jsonButton.click();
        this.formElement.setValue(this.data.formData ? JSON.parse(this.data.formData) : '');

    },
    onChange: function (event) {
        this.event.change = event;
    },
    change: function (type, data) {
        if (this.data.hasOwnProperty(type) && (this.data[type] != data)) {
            this.data[type] = data;
            this.event.change(type, data, this.data.id);
        };
    },
    setOldData: function () {
        this.event.getOldDate(this.data.id, (data) => {
            this.set(data);
            setTimeout(() => {
                for (const key in this.data) {
                    if (this.data.hasOwnProperty(key)) {
                        const item = this.data[key];
                        this.event.change(key, item, this.data.id);
                        // this.change(key, item);
                    }
                }
            }, 20);

            console.log(data);
        });
    },
    onSend: function (event) {
        this.event.send = event;
    },
    setSendStatus: function (status, body, id) {
        if (id == this.data.id) {
            if (status == 'Sendend') {
                this.sendingEle.css('display', 'none');
                this.sendEle.css('display', 'block');
                this.formatResponse(body);
            } else if (status == 'Sending') {
                this.sendingEle.css('display', 'block');
                this.sendEle.css('display', 'none');
                this.formatResponse(body, true);
            }
        };
    },
    send: function () {
        this.urlSelect.get((error, url) => {
            if (url === null || url == '(空)') {
                url = '';
            };
            var status = this.event.send(this.data.id, url);
            if (status) {
                this.setSendStatus('Sending', null, this.data.id);
            };
        });
    },
    onCancel: function (event) {
        this.event.cancel = event;
    },
    cancel: function () {
        this.event.cancel(this.data.id);
        this.sendingEle.css('display', 'none');
        this.sendEle.css('display', 'block');
        this.responseLoading.css('display', 'none');
        var text = 'Status:-- &nbsp; Time:-- ms &nbsp; Size:--B';
        this.responseFormat.html(text);
        this.ResponseEditor.setValue('');
    },
    reconvert: function (str) {
        str = str.replace(/(\\u)(\w{1,4})/gi, function ($0) {
            return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
        });
        str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) {
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
        });
        str = str.replace(/(&#)(\d{1,6});/gi, function ($0) {
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
        });
        return str;
    },
    formatResponse: function (result, status) {
        if (status) {
            this.responseLoading.css('display', 'block');
        } else {
            this.responseLoading.css('display', 'none');
        };
        if (!result) {
            var text = 'Status:-- &nbsp; Time:-- ms &nbsp; Size:--B';
            this.responseFormat.html(text);
            this.ResponseEditor.setValue('');
            return;
        };
        var _this = this;
        if (verifty.type(result.body, 'object') || verifty.type(result.body, 'array')) {
            result.body = JSON.stringify(result.body);
            result.size = result.body.length;
        };
        var text = 'Status:' + result.status + ' &nbsp; Time:' + result.time + ' ms &nbsp; Size:' + result.size + ' B';
        this.responseFormat.html(text);
        this.ResponseEditor.setValue(result.body ? this.reconvert(result.body) : '');
        var setCacheValue = function (key, value) {
            window.__CacheValue__[key] = value;
        };
        try {
            var res = JSON.parse(result.body);
            var data = this.testEditor.getValue();
            eval(data);
        } catch (error) {

        };
        setTimeout(() => {
            beautify(this.ResponseEditor);
        }, 20);
    },
    showMark: function () {
        this.Mark.css('display', 'block');
        this.status = false;
    },
    hideMark: function () {
        this.Mark.css('display', 'none');
        this.status = true;
    }
};


module.exports = function () {
    return new contentEX();
};